package com.hzsk.lisence.service.impl;

import com.hzsk.lisence.service.AsyncTaskService;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Description :
 * @Date : 2024/9/7
 * @Author : ChenJin
 * @Version : v1.0.0
 **/
@Slf4j
@Service
public class AsyncTaskServiceImpl implements AsyncTaskService {

    @Value("${share-directory.host}")
    private String shareHost;

    @Value("${share-directory.username}")
    private String shareUsername;

    @Value("${share-directory.password}")
    private String sharePassword;

    @Value("${share-directory.base-path}")
    private String shareBasePath;
    
    @Async
    @Override
    public void asyncUploadFile(FileInputStream fileInputStream, String filePath, String fileName) {
        log.info("异步上传文件至共享文件夹开始");
        String remoteUrl =  "smb://" + shareUsername + ":" + sharePassword + "@" + shareHost + shareBasePath;
        try{
            SmbFile smbFileFolder = new SmbFile(remoteUrl + filePath);
            if (!smbFileFolder.exists()){
                smbFileFolder.mkdir();
            }
            assert fileName != null;
            SmbFile smbFile = new SmbFile(remoteUrl + filePath + "/" +fileName);
            SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(smbFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                smbFileOutputStream.write(buffer, 0, bytesRead);
            }
            smbFileOutputStream.flush();
            smbFileOutputStream.close();
        }catch (Exception e){
            log.error("异步上传文件至共享文件夹失败:{}",e.getMessage());
            e.printStackTrace();
        }
        log.info("异步上传文件至共享文件夹结束");
        
    }

    @Override
    public void asyncDeleteFile(String filePath) {
        log.info("异步删除共享文件开始");
        String remoteUrl =  "smb://" + shareUsername + ":" + sharePassword + "@" + filePath;
        try {
            SmbFile smbFile = new SmbFile(remoteUrl);
            smbFile.delete();
        }catch (Exception e){
            log.error("异步删除文件失败:{}",e.getMessage());
            e.printStackTrace();
        }
        log.info("异步删除共享文件结束");
    }
}
